package org.ring.config.client;

import org.ring.common.URL;
import org.ring.common.transport.ClientTransport;
import org.ring.common.transport.Connection;
import org.ring.common.transport.MessageHandler;
import org.ring.common.transport.DefaultMessageHandlerRegistry;
import org.ring.common.transport.TransportConfig;
import org.ring.config.common.GetRequest;
import org.ring.config.common.GetResponse;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @since 2024-08-20 19:25
 */
public class ConfigClient {

    private ServerListManager serverListManager;
    private ClientTransport clientTransport;
    private AtomicReference<Connection> connectionReference = new AtomicReference<>();

    ConfigListener configListener ;
    void configListener(ConfigListener configListener){
        this.configListener = configListener;
    }



    public void start(){
        DefaultMessageHandlerRegistry handlerRegistry = new DefaultMessageHandlerRegistry();

        TransportConfig transportConfig = new TransportConfig();
        serverListManager = new ServerListManager() {
            @Override
            public Endpoint next() {
                return new Endpoint("127.0.0.1",12300);
            }
        };
        clientTransport = new ClientTransport(transportConfig);
        clientTransport.handlerRegistry(handlerRegistry);

        handlerRegistry.register(GetResponse.class, new MessageHandler() {
            @Override
            public CompletableFuture handle(Connection connection, Object input) {
                System.out.println(input);
                return CompletableFuture.completedFuture(input);
            }
        });

        Endpoint endpoint = serverListManager.next();
        URL url = new URL("",endpoint.getAddress(),endpoint.getPort());
        Connection connection = clientTransport.connect(url);
        connectionReference.set(connection);

    }

    public String getConfig(String namespace,String configId) throws Exception{
        GetRequest getRequest = new GetRequest();
        getRequest.setNamespace(namespace);
        getRequest.setConfigId(configId);
        CompletableFuture responseFuture = connectionReference.get().request(getRequest,1,null);
        GetResponse responseMessage = (GetResponse)responseFuture.get();
        return responseMessage.getContent();
    }

    public String getConfigAndListener(String namespace,String configId,ConfigListener listener) throws Exception{
        GetRequest getRequest = new GetRequest();
        getRequest.setNamespace(namespace);
        getRequest.setConfigId(configId);

        CompletableFuture responseFuture = connectionReference.get().request(getRequest,1,null);
        GetResponse responseMessage = (GetResponse)responseFuture.get();
        return responseMessage.getContent();
    }


}
